package com.sairobo.admin.modules.srblive.service.impl;

import com.sairobo.admin.modules.srblive.pojo.param.FileParam;
import com.sairobo.admin.modules.srblive.service.FileService;
import com.sairobo.admin.modules.srblive.utils.LivePropertyUtil;
import com.sairobo.base.common.constant.MsgConstant;
import com.sairobo.base.common.entity.R;
import com.sairobo.base.common.utils.CommonUtils;
import com.sairobo.base.common.utils.MultiUpload;
import com.sairobo.base.modules.sys.entity.SysAttach;
import com.sairobo.base.modules.sys.manager.SysAttachManager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;


/**
 * 用户信息
 *
 * @author admin
 * @email sairobo
 * @url www.sairobo.com
 * @date 2018年1月11日 上午11:05:49
 */
@Service("fileServiceImpl")
public class FileServiceImpl implements FileService {

    @Autowired
    SysAttachManager sysAttachManager;

    @Override
    public R multiUpload(HttpServletRequest request, MultipartFile file, FileParam param) throws IOException, InstantiationException, IllegalAccessException {
        String rootPath = LivePropertyUtil.instance.getMessage("ppt.upload.path");
        List attachs = new ArrayList<>();
        //类似 rootPath/20171207/
//        String midPath = DateHelper.getTime(DateHelper.DATE_FORMAT_6) + "/";
//        String pathPrefix = getWebContextPath(request) + rootPath + midPath;
//        File f = new File(pathPrefix);
//        if (!f.exists()) f.mkdir();//不存在就创建文件夹

        Map<String, Object> map = new HashMap<String,Object>();
        MultiUpload multiUpload =new MultiUpload() {
            protected void wrapper(Object obj, Map<String, Object> map) {
                SysAttach attach=(SysAttach)obj;
                String path = rootPath + rename(file.getOriginalFilename());
                attach.setFilePath(path.replace(getWebContextPath(request),""));
                attach.setFileName(file.getOriginalFilename());
                attach.setFileSize(file.getSize()+"");
            }
        };
        attachs =  multiUpload.multiUpload(request, rootPath, SysAttach.class, map);
        if(CollectionUtils.isEmpty(attachs))
        {
            return R.error(MsgConstant.MSG_INIT_UPLOAD);
        }
        return CommonUtils.msg(attachs);
    }


    private String rename(String orgName) {
        String head = UUID.randomUUID().toString().replace("-", "");
        return head + orgName.substring(orgName.lastIndexOf("."));
    }

    private static String getWebContextPath(HttpServletRequest request){
        String ctxPath = request.getSession().getServletContext()
                .getRealPath("/");
        return ctxPath;
    }

}
